<template>
  <div class="configure-detail">
    <Form
      :model="detailInfo"
      class="ivu-form-no-margin-bottom"
      ref="configForm"
      :rules="rules"
      :label-width="80"
      :disabled="handleType === 'detail'"
    >
      <Row :gutter="32" class="code-row-bg">
        <Col span="12">
          <Form-item prop="dataId" :label="$t('module.configureList.dataId')">
            <Input :maxlength="127" :disabled="disabledField"  v-model="detailInfo.dataId" />
          </Form-item>
        </Col>
        <Col span="12">
          <Form-item prop="group" :label="$t('module.configureList.group')">
            <Input :maxlength="127" :disabled="disabledField"  v-model="detailInfo.group" />
          </Form-item>
        </Col>
        <Col span="12">
          <Form-item prop="appName" :label="$t('module.configureList.belongApp')">
            <Input :maxlength="127"  v-model="detailInfo.appName" />
          </Form-item>
        </Col>
        <Col span="12">
          <Form-item prop="configTags" :label="$t('module.configureList.configTags')">
            <Select
              :placeholder="configTagsList.length ? '请选择' : '请输入标签'"
              :value="configTags"
              filterable
              multiple
              allow-create
              @on-create="handleCreate"
              @on-change="handleChange"
            >
              <Option v-for="(item, index) in configTagsList" :value="item.value" :key="index">{{ item.label }}</Option>
            </Select>
          </Form-item>
        </Col>
        <Col span="24">
          <Form-item prop="desc" :label="$t('module.configureList.description')">
            <Input :maxlength="128" v-model="detailInfo.desc"  :rows="3" type="textarea" />
          </Form-item>
        </Col>
        <Col span="24" v-if="handleType === 'detail'">
          <Form-item prop="md5" label="MD5">
            <Input v-model="detailInfo.md5"  />
          </Form-item>
        </Col>
        <Col span="24">
          <Form-item prop="type" :label="$t('module.configureList.type')">
            <RadioGroup v-model="detailInfo.type">
              <Radio v-for="(item, index) in typeList" :label="item.value" :key="index">
                <span>{{ item.label }}</span>
              </Radio>
            </RadioGroup>
          </Form-item>
        </Col>
        <Col span="24">
          <Form-item :required="true" :label="$t('module.configureList.content')" :error="contentError">
            <div class="code_wrap">
              <code-editor ref="codeEditor" :config="editorConfig" v-model="detailInfo.content"></code-editor>
            </div>
          </Form-item>
        </Col>
      </Row>
    </Form>
  </div>
</template>

<script>
import locales from "./locales";
import { nacosConfigApi } from "@/api/nacosList";
import codeEditor from "@/components/common/CodeEditor/index.vue";

export default {
  name: "configureDetail",
  mixins: [locales],
  props: ["row", "handleType", "namespaceId"],
  components: {
    codeEditor
  },
  computed: {
    editorConfig() {
      return {
        readOnly: this.handleType === "detail",
        language: this.detailInfo.type
      };
    },
    disabledField() {
      return this.handleType === "edit";
    }
  },
  data() {
    let buttons = [];
    if (this.handleType !== "detail") {
      buttons.push({
        text: this.$t("common.pub"),
        theme: "primary",
        handle: () => {
          this.save();
        }
      });
      buttons.push({
        text: this.$t("common.close"),
        handle: () => {
          this.$emit("Close");
        }
      });
    }


    function specialChartdValidate(rule, value, callback) {
      if (/[\s$^\s@#￥%&*\s]+/g.test(value)) {
        return callback(new Error("不允许非法字符"));
      }
      callback();
    }

    return {
      detailInfo: {
        dataId: "",
        group: "",
        appName: "",
        configTags: [],
        desc: "",
        md5: "",
        content: "",
        id: "",
        type: "text"
      },
      configTags: [],
      configTagsList: [],
      contentError: "",
      configTagsCopy: [],
      typeList: [
        { value: "text", label: "TEXT" },
        { value: "json", label: "JSON" },
        { value: "xml", label: "XML" },
        { value: "yaml", label: "YAML" },
        { value: "html", label: "HTML" },
        { value: "properties", label: "Properties" }
      ],
      actions: buttons,
      disabled: false,
      rules: {
        dataId: [
          { required: true, message: "请输入DataId", trigger: "blur" },
          { maxlength: 127, message: "允许最大输入字符长度为127", trigger: "blur" },
          { validator: specialChartdValidate, trigger: "blur" }
        ],
        group: [
          { required: true, message: "请输入group", trigger: "blur" },
          { maxlength: 127, message: "允许最大输入字符长度为127", trigger: "blur" },
          { validator: specialChartdValidate, trigger: "blur" }
        ],
        appName: [
          // { required: true, message: '请输入归属应用', trigger: 'blur' },
        ]
      }
    };
  },
  mounted() {
    this.setDialog();
    this.init();
  },
  methods: {
    setDialog() {
      if (this.handleType === "detail") {
        this.$emit("SetTitle", this.$t("module.configureList.configureDetail"));
      }
      if (this.handleType === "edit") {
        this.$emit("SetTitle", this.$t("module.configureList.editConfigure"));
      }
      if (this.handleType === "add") {
        this.$emit("SetTitle", this.$t("module.configureList.createConfigure"));
      }
      this.$emit("SetPageWidth", 900);
      // this.$emit("SetPageMinHeight", 500);
      this.$emit("SetPageActions", this.actions);
    },
    init() {
      if (this.handleType !== "add") {
        this.getDetail();
      }
    },
    getDetail() {
      nacosConfigApi
        .getConfigDetail({
          namespaceId: this.row.namespaceId,
          appName: this.row.appName,
          dataId: this.row.dataId,
          group: this.row.group
        })
        .then(res => {
          for (let key of Object.keys(this.detailInfo)) {
            this.detailInfo[key] = res.data[key];
          }
          this.configTags = this.detailInfo.configTags ? this.detailInfo.configTags.split(",") : [];
          this.configTagsList = this.detailInfo.configTags
            ? this.detailInfo.configTags.split(",").map(item => ({ label: item, value: item }))
            : [];
          this.$refs.codeEditor.setValue(this.detailInfo.content);
        });
    },
    save() {
      this.$refs.configForm.validate(valid => {
        if (!this.detailInfo.content) {
          this.contentError = "请输入配置内容";
          return;
        }
        if (valid) {
          const params = { ...this.detailInfo };
          params.configTags = this.configTagsCopy ? this.configTagsCopy.join(",") : "";
          params.namespaceId = this.namespaceId;
          if (this.configTagsCopy.length > 5) {
            this.$message.error({
              content: "标签数量不能大于5个",
              duration: 3
            });
            return false;
          }
          if (this.detailInfo.content && this.detailInfo.type === "json") {
            try {
              JSON.parse(this.detailInfo.content); // 如果不是json字符串就会抛异常
              this.createOrEdit(params);
            } catch (e) {
              new $confirm("配置信息可能有语法错误, 确定提交吗?", this).then(() => {
                this.createOrEdit(params);
              });
            }
            return false;
          }
          this.createOrEdit(params);
        }
      });
    },
    createOrEdit(params) {
      if (this.handleType === "add") {
        delete params.id;
        nacosConfigApi.getConfigDetail({
          namespaceId: params.namespaceId,
          dataId: params.dataId,
          group: params.group
        }).then(res => {
          if (!!res.data.id) {
            this.$message.error({
              content: "配置已存在，试试别的Data ID和Group的组合吧",
              duration: 3
            });
          } else {
            nacosConfigApi.addConfig(params).then(res => {
              if (res.data) {
                this.$message.success({
                  content: this.$t("common.saveSuccess"),
                  duration: 3
                });
                this.$emit("Close", true);
              } else {
                this.$message.error({
                  content: "操作失败",
                  duration: 3
                });
              }
            });
          }
        })
      }
      if (this.handleType === "edit") {
        nacosConfigApi.editConfig(params).then(res => {
          console.log(res, "edit");
          if (res.data) {
            this.$message.success({
              content: this.$t("common.saveSuccess"),
              duration: 3
            });
            this.$emit("Close", true);
          } else {
            this.$message.error({
              content: "操作失败",
              duration: 3
            });
          }
        });
      }
    },
    handleCreate(val) {
      this.configTagsList.push({
        value: val,
        label: val
      });
    },
    handleChange(val) {
      this.configTagsCopy = val;
    }
  }
};
</script>

<style scoped lang="less">
.code_wrap {
  height: 450px;
  width: 100%;
  border: 1px solid #cccccc;
}
</style>
